/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse;

import java.sql.*;

public class DiskManager {

	public static synchronized double reclaimSpaceFromDataInfo(String globalDir)
			throws Exception {
		MetaDatabase mdb = MetaDatabase.create();

		if (!globalDir.endsWith("/"))
			globalDir += "/";

		Statement s = mdb.createStatement();
		String sql = "select * from Data_Info where path like '"
				+ globalDir
				+ "%' and path not like '%.gz' order by Index_Date desc, Run desc limit 1";

		ResultSet rs = s.executeQuery(sql);
		if (rs.next()) {
			String path = rs.getString("Path");
			System.out.println("DiskManager: GZipping '" + path + "'");
			NetFSEUtil.execAndWait("gzip " + path);
			rs.close();
			s.execute("update Data_Info set path ='" + path
					+ ".gz' where path='" + path + "'");
		} else {

			System.out
					.println("DiskManager: no indexed data to compress, trying data files.");
			rs.close();

			
		}
		s.close();
		mdb.closeConnection();
		return NetFSE.getDiskFullPercent(globalDir);

	}

	public static synchronized double reclaimSpaceFromDataFiles(String dataFileDir)
			throws Exception {
		MetaDatabase mdb = MetaDatabase.create();
		Statement s = mdb.createStatement();
		System.out.println("DiskManager: trying to compress data files.");
		String sql = "select * from Data_Files where path like '" + dataFileDir + "%' and Node_ID ="
				+ NetFSE.NODE_ID
				+ " and path not like '%.gz' order by file_id asc limit 1";

		ResultSet rs = s.executeQuery(sql);
		if (rs.next()) {
			String path = rs.getString("Path");
			System.out.println("DiskManager: GZipping '" + path + "'");
			NetFSEUtil.execAndWait("gzip " + path);
			rs.close();
			s.execute("update data_files set path ='" + path
					+ ".gz' where path='" + path + "'");
		}

		s.close();
		mdb.closeConnection();
		return NetFSE.getDiskFullPercent(dataFileDir);

	}
}
